package com.rbs.dao.Impl;

import com.rbs.dao.PhoneDao;
import com.rbs.entity.Phone;
import com.rbs.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class PhoneDaoImpl implements PhoneDao {
    @Override
    public List<Phone> selectAll() {
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        Phone phone = null;
        List<Phone> phoneList = new ArrayList<>();
        try {
            conn = JDBCUtils.getConn();
            //创建preparedStatement
            String sql = "select * from t_phone";
            psmt = conn.prepareStatement(sql);
            //执行sql语句
            rs = psmt.executeQuery();
            //处理结果集
            while (rs.next()){
                phone = new Phone();
                phone.setPid(rs.getInt("pid"));
                phone.setPname(rs.getString("pname"));
                phone.setPrice(rs.getBigDecimal("price"));
                phone.setBrandId(rs.getInt("brand_id"));
                phone.setState(rs.getInt("state"));
                phoneList.add(phone);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return phoneList;
    }

    @Override
    public List<Phone> selectByPage(int start, int PageSize) {
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        List<Phone> listPhone = new ArrayList<>();
        try {
            conn = JDBCUtils.getConn();
            String sql = "select * from t_phone limit ?,?";
            psmt = conn.prepareStatement(sql);
            psmt.setInt(1,start);
            psmt.setInt(2,PageSize);
            rs = psmt.executeQuery();
            while (rs.next()){
                Phone phone = new Phone();
                phone.setPid(rs.getInt("pid"));
                phone.setPname(rs.getString("pname"));
                phone.setPrice(rs.getBigDecimal("price"));
                phone.setState(rs.getInt("state"));
                phone.setBrandId(rs.getInt("brand_id"));
                listPhone.add(phone);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return listPhone;
    }

    @Override
    public int selectCount() {
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        int count = 0;
        try {
            conn = JDBCUtils.getConn();
            String sql = "select count(*) con from t_phone";
            psmt = conn.prepareStatement(sql);
            rs = psmt.executeQuery();
            while (rs.next()){
                count = rs.getInt("con");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return count;
    }
}
